package com.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.mall.common.constants.TokenConstants;
import com.mall.common.domain.MallProductSpell;
import com.mall.common.domain.MallUser;
import com.mall.common.utils.JwtUtils;
import com.mall.product.mapper.ProductSpellMapper;
import com.mall.product.service.ProductSpellService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author wangy
 * @version 1.0
 * @description: TODO
 */
@Service
public class ProductSpellServiceImpl implements ProductSpellService {
    @Resource
    private ProductSpellMapper productSpellMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final int STATUS = 3;
    @Override
    public List<MallProductSpell> selectProductSpellList(MallProductSpell mallProductSpell) {
        return productSpellMapper.selectProductSpellList(mallProductSpell);
    }

    @Override
    public void addProductSpell(MallProductSpell mallProductSpell) {
        String token = request.getHeader(TokenConstants.TOKEN);
        if (token != null) {
            String userKey = JwtUtils.getUserKey(token);
            String userJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
            MallUser mallUser = JSON.parseObject(userJson, MallUser.class);
            if (mallUser != null) {
                mallProductSpell.setSponsor(mallUser.getId());
            }
            mallProductSpell.setInitiationTime(new Date());
            productSpellMapper.addProductSpell(mallProductSpell);
        }
    }

    @Override
    public void updateProductSpell(MallProductSpell mallProductSpell) {

        rabbitTemplate.convertAndSend("sendCode", JSON.toJSONString(mallProductSpell));
        productSpellMapper.updateProductSpell(mallProductSpell);
    }

    /**
     * 拼单失败
     */
    @Override
    public void fail() {
        Date date = new Date();
        List<MallProductSpell> failList = productSpellMapper.fail(date);
        for (MallProductSpell mallProductSpell : failList) {

            rabbitTemplate.convertAndSend("sendATextMessage", JSON.toJSONString(mallProductSpell));
            mallProductSpell.setStatus(STATUS);
            productSpellMapper.updateProductSpell(mallProductSpell);
        }


    }
}
